<template>
	<section>
    <!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
        <!--<el-form-item>
				<el-select v-model="filters.keyword" clearable placeholder="请选择地区" style="width:120px">
						<el-option
						v-for="item in cityOptions"
						:key="item.id"
						:label="item.label"
						:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
        -->
        	<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入城市名称，支持模块搜索" style="width:240px;"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="handleFilter">查询</el-button>
				</el-form-item>
			</el-form>
		</el-col>
    <p style="width: 100%;padding-top: 80px; text-align: center;" v-show="listLoading">
      加载中...
    <p>
    <div style="padding-top: 80px;" v-show="!listLoading">
        <el-tree
          :data="treeData"
          node-key="id"
          show-checkbox
          default-expand-all
          :expand-on-click-node="false"
          :render-content="renderContent">
        </el-tree>
      </div> 
        		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="父节点ID" prop="parentId">
					<el-input v-model="addForm.parentId" readonly style="width:200px" auto-complete="off" class="form_input"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="addForm.name" auto-complete="off" style="width:200px" class="form_input"></el-input>
				</el-form-item>
        <el-form-item label="城市（原产地）" prop="cityId">
            <el-select v-model="addForm.cityId" placeholder="请选择">
            <el-option
              v-for="item in cfoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="标题" prop="title">
					<el-input v-model="addForm.title" auto-complete="off" class="form_input"></el-input>
				</el-form-item>			
        <el-form-item label="内容" prop="nameDetail">
					<el-input v-model="addForm.nameDetail" auto-complete="off" class="form_input"></el-input>
				</el-form-item>
        <el-form-item
        v-for="(attrkey, index) in addForm.attrkeys"
        :label="'属性名' + index"
        :key="attrkey.key"
        :prop="'attrkeys.' + index + '.value'"
        :rules="{required: true, message: '属性不能为空', trigger: 'blur'}">
        <el-input v-model="attrkey.value"></el-input><el-button @click.prevent="removeKey1(attrkey)">删除</el-button>
      </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button @click.native="addKey1">新增属性</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>


    <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="父节点ID" prop="parentId">
					<el-input v-model="editForm.parentId" readonly style="width:200px" auto-complete="off" class="form_input"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off" style="width:200px" class="form_input"></el-input>
				</el-form-item>
        <el-form-item label="城市（原产地）" prop="cityId">
            <el-select v-model="editForm.cityId" placeholder="请选择">
            <el-option
              v-for="item in cfoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="标题" prop="title">
					<el-input v-model="editForm.title" auto-complete="off" class="form_input"></el-input>
				</el-form-item>
				
        <el-form-item label="内容" prop="nameDetail">
					<el-input v-model="editForm.nameDetail" auto-complete="off" class="form_input"></el-input>
				</el-form-item>
        <el-form-item
        v-for="(attrkey, index) in editForm.attrkeys"
        :label="'属性名' + index"
        :key="attrkey.key"
        :prop="'attrkeys.' + index + '.value'"
        :rules="{required: true, message: '属性不能为空', trigger: 'blur'}">
        <el-input v-model="attrkey.value"></el-input><el-button @click.prevent="removeKey(attrkey)">删除</el-button>
      </el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button @click.native="addKey">新增属性</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
  
</template>

<script>
import util from "../../common/js/util";
import cfg from "../../cfg/const";
//import NProgress from 'nprogress'
import {
  fetchCategorys,
  removeCategory,
  editCategory,
  addCategory,
  getAllCitys
} from "../../api/api";

export default {
  data() {
    return {
      filters: {
        keyword: undefined
      },
      cityOptions: cfg.cityOptions,
      cfoptions: [],
      list: [],
      total: 0,
      currentPage: 1,
      listLoading: false,
      treeData: [],
      sels: [], //列表选中列
      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: "名称", trigger: "blur" }],
        title: [{ required: true, message: "标题", trigger: "blur" }],
        nameDetail: [{ required: false, message: "详情", trigger: "blur" }]
      },

      //新增界面数据
      addForm: {
        parentId: undefined,
        name: "",
        title: "",
        nameDetail: "",
        cityId: undefined,
        //分类属性值
        attrkeys: [{ value: ''}]
      },

      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [{ required: true, message: "名称", trigger: "blur" }],
        title: [{ required: true, message: "标题", trigger: "blur" }],
        nameDetail: [{ required: false, message: "详情", trigger: "blur" }]
      },

      //编辑界面数据
      editForm: {
        id: undefined,
        parentId: undefined,
        name: "",
        title: "",
        nameDetail: "",
        cityId: undefined,
        attrkeys: [{ value: ''}]
      }
    };
  },
  methods: {
    getCitys() {
      getAllCitys().then(res => {
        let arr = [];
        res.data.data.forEach(function(val,index){
          arr.push({"value": val.cityId,"label":val.cityName});
        });
        this.cfoptions = arr;
      })
    },

    handleFilter() {
      this.getList();
    },
    renderContent(h, { node, data, store }) {
      if (!data) {
        return "";
      }
      let title =
        data.title && data.title.length > 15
          ? data.title.substr(0, 12) + "..."
          : data.title;
      let detail =
        data.detail && data.detail.length > 15
          ? data.detail.substr(0, 12) + "..."
          : data.detail;
      return (
        <span class="custom-tree-node">
          <span>
            {data.name}（ID:{data.id}）
            {3 == node.level ? "；标题：" + title : ""}
            {3 == node.level ? "（" + detail + "）" : ""}
          </span>
          <span style="margin-left:20px">
            {3 !== node.level ? (
              <el-button
                size="mini"
                type="text"
                on-click={() => this.addChildNode(data)}
              >
                添加子类
              </el-button>
            ) : (
              ""
            )}
            <el-button
              size="mini"
              type="text"
              on-click={() => this.editNode(data)}
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.removeNode(data)}
            >
              {1 == data.status ? "首页显示" : "首页隐藏"}
            </el-button>
          </span>
        </span>
      );
    },
    //获取用户列表
    getList() {
      let para = {
        currentPage: this.currentPage,
        cityId: this.keyword
      };
      this.listLoading = true;
      //NProgress.start();
      fetchCategorys(para).then(res => {
        console.log(JSON.stringify(res));
        this.total = res.data.total;
        this.list = res.data.categorys;
        this.treeData = util.convertArrayToTree(
          res.data.categorys,
          1,
          "id",
          "parentId",
          "children"
        );
        this.listLoading = false;
        //NProgress.done();
      });
    },
    //删除
    removeNode: function(data) {
      this.$confirm("确认删除分类吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = { data: {id: data.id}};
          removeCategory(para).then(res => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    //显示新增界面
    addChildNode: function(data) {
      this.addFormVisible = true;
      this.getCitys();
      this.addForm = {
        parentId: data.id,
        name: "",
        cityId: "",
        title: "",
        nameDetail: "",
        attrkeys: [{ value: '',key: Date.now()}]
      };
    },
    //新增
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            let arr = [];
            this.addForm.attrkeys.forEach(function(val,index){
              arr.push(val);
            });
            para.keys = JSON.stringify(arr);
            console.log(para.keys);
            addCategory(para).then(res => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: "提交成功",
                type: "success"
              });
              this.$refs["addForm"].resetFields();
              this.addFormVisible = false;
              this.getList();
            });
          });
        }
      });
    },
    //显示编辑界面
    editNode: function(data) {
      this.editFormVisible = true;
      this.getCitys();
      data.nameDetail = data.detail;
      data.attrkeys = JSON.parse(data.keys);
      console.log("编辑界面数据填充：")
      console.log(data);
      this.editForm = Object.assign({}, data);
    },
    //编辑
    editSubmit: function() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            para.keys = JSON.stringify(para.attrkeys);
            editCategory(para).then(res => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: "提交成功",
                type: "success"
              });
              this.$refs["editForm"].resetFields();
              this.editFormVisible = false;
              this.getList();
            });
          });
        }
      });
    },
    removeKey1(item) {
      var index = this.addForm.attrkeys.indexOf(item);
      if (index !== -1) {
        this.addForm.attrkeys.splice(index, 1);
      }
      console.log(this.addForm.attrkeys);
    },
    addKey1() {
      //console.log(this.addForm);
      this.addForm.attrkeys.push({
        value: '',
        key: Date.now()
      });
      console.log(this.addForm.attrkeys);
    },
    removeKey(item) {
      var index = this.editForm.attrkeys.indexOf(item);
      if (index !== -1) {
        this.editForm.attrkeys.splice(index, 1);
      }
      console.log(this.editForm.attrkeys);
    },
    addKey() {
      this.editForm.attrkeys.push({
        value: '',
        key: Date.now()
      });
      console.log(this.editForm.attrkeys);
    }
  },
  mounted() {
    this.getList();
  }
};
</script>

<style scoped>
</style>